//
//  ZDTabBar.m
//  1012GiftTips
//
//  Created by Apple on 15/10/15.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZDTabBar.h"
#import "ZDTabBarButton.h"

@interface ZDTabBar ()

@property (nonatomic, weak) ZDTabBarButton *selectedButton;

@end

@implementation ZDTabBar

- (void)addTabBarButtonWithNormalName:(NSString *)normalName andSelectedName:(NSString *)selectedName andTitle:(NSString *)title
{
    ZDTabBarButton *btn = [[ZDTabBarButton alloc] init];
    
//    btn.backgroundColor = [UIColor whiteColor];
    
    //设置按钮的image
    [btn setImage:[UIImage imageNamed:normalName] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:selectedName] forState:UIControlStateSelected];
    
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    
    //为按钮绑定点击事件
    [btn addTarget:self action:@selector(tabBarButtonClick:) forControlEvents:UIControlEventTouchDown];
    
    //默认选中第一个按钮
    if (self.subviews.count == 0)
    {
        btn.selected = YES;
        self.selectedButton = btn;
    }
    
    //设置按钮的tag值
    btn.tag = self.subviews.count;
    
    //添加到tabBar中
    [self addSubview:btn];
}

//tabBarButton按钮点击事件
- (void)tabBarButtonClick:(ZDTabBarButton *)button
{
    self.selectedButton.selected = NO;
    button.selected = YES;
    self.selectedButton = button;
    
    //调用block，切换控制器
    if (self.block)
    {
        self.block(button.tag);
    }
}

//布局子控件的frame
- (void)layoutSubviews
{
    [super layoutSubviews];
    
    NSInteger count = self.subviews.count;
    
    CGFloat btnW = ZDScreenSize.width / count;
    CGFloat btnH = self.frame.size.height;
    CGFloat btnY = 0;
    
    
    for (NSInteger index = 0; index < count; index++)
    {
        ZDTabBarButton *btn = self.subviews[index];
        
        CGFloat btnX = index * btnW;
        
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
    }
}


@end
